const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session')
const logger = require('morgan');
const cors = require('cors');
// const musicRouter = require('./routes/main/music');
const WebSocket = require('./routes/common/websocket')
const db = require('./routes/common/db');
const upload = require('./routes/common/upload');
let app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use(cookieSession({
    name: 'mycookie',
    // maxAge: 1000 * 30,
    keys: ['aa', 'bb']
}))

app.all('*', function(req, res, next) {
    // 请求源 ajax http://localhost:8080
    // res.header("Access-Control-Allow-Origin", "http://192.168.43.48:8080");
    // res.header("Access-Control-Allow-Origin", "http://49.234.36.18");
    res.header("Access-Control-Allow-Origin", "http://localhost:8080");

    // 请求头  x-token
    res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With, Current-Page");
    // 请求方法  post get put delete patch
    res.header("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS");
    res.header("X-powered-By", '3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Access-Control-Allow-Credentials", 'true');
    // 下一步
    if (req.method == 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});
app.use(WebSocket)
app.use('/upload', upload)
app.use(db)
app.use('/', require('./routes/main/index'));
app.use('/users', require('./routes/main/users'));
app.use('/square', require('./routes/main/square'));
// app.use('/song', musicRouter);
app.use('/chat', require('./routes/main/chat'));
app.use('/mall', require('./routes/main/mall'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;